/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.weather;

import java.util.HashSet;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.modpircbot.ModPircbot;
import org.modpircbot.callback.MessageHandler;
/**
 *
 * @author tangd
 */
public class WeatherModule implements MessageHandler
{
    public static final int GOOGLE = 0,
            WUNDERGROUND = 1;
    WeatherFetcher weatherModule;
    ModPircbot mainBot;
    HashSet<String> enabledChannels = new HashSet<String>();
    String defaultSearch;
    boolean _metricFirst;
    public void loadConfig(Elements configData) {
        Elements channels = configData.select("enabledChannel");
        for(Element e : channels) {
          enabledChannels.add(e.attr("name"));
        }
        defaultSearch = configData.select("default").attr("location");
        _metricFirst = configData.select("useMetric").attr("value").equals("1");
        int weatherSelector = Integer.parseInt(configData.select("source").attr("value"));
        switch(weatherSelector) {
           case WeatherModule.GOOGLE: {
              weatherModule = new Google(_metricFirst);
              break;
           }
           case WeatherModule.WUNDERGROUND: {
              weatherModule = new Wunderground(_metricFirst);
              break;
           }
           default: {
              weatherModule = new Wunderground(_metricFirst);
           }
        }
    }

    public void onMessage(String channel, String sender, String login, String hostname, String message) {
        if(enabledChannels.contains(channel)) {
            if(message.equals("!w")) {
                mainBot.sendMessage(channel, weatherModule.getWeather(defaultSearch));
            }
            else if(message.startsWith("!w ")) {
                mainBot.sendMessage(channel, weatherModule.getWeather(message.substring(3)));
            }
            else if(message.equals("!forecast")) {
                mainBot.sendMessage(channel, weatherModule.getForecast(defaultSearch));
            }
            else if(message.startsWith("!forecast ")) {
                mainBot.sendMessage(channel, weatherModule.getForecast(message.substring(10)));
            }
        }
    }
    public void register(ModPircbot b) {
        mainBot = b;
        mainBot.messageHandlers.add((MessageHandler)this);
    }
}
